home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15313 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: user2.mnsinc.com!huang
  2. From: huang@mnsinc.com (Szu-Wen Huang)
  3. Newsgroups: alt.msdos.programmer,comp.lang.c,comp.lang.pascal.misc
  4. Subject: Re: typecasting preferences
  5. Date: 18 Apr 1996 12:56:01 GMT
  6. Organization: Monumental Network Systems
  7. Distribution: world
  8. Message-ID: <4l5e51$1s4@news1.mnsinc.com>
  9. References: <4l020g$i9j@srvr1.engin.umich.edu> <Pine.A32.3.91.960416145209.106109C-100000@black.weeg.uiowa.edu> <4l4ldb$nkl@srvr1.engin.umich.edu>
  10. NNTP-Posting-Host: user.mnsinc.com
  11. X-Newsreader: TIN [version 1.2 PL2]
  12.  
  13. HASDI RODZMANN HASHIM (hasdi@news-server.engin.umich.edu) wrote:
  14. [snip]
  15. : The way I understand it, type-conversion is to transform the bits of one
  16. : variable so that it is representable as the type to be converted into. eg. 
  17. : (int)my_float. type-casting doesn't transform the bits at all, but force
  18. : the compiler to treat that variable as the specified type... which is
  19. : highly unportable. Why would anyone want to typecast then? Can somebody
  20. : clarify this for me? 
  21.  
  22. Sure.  You typecast when you know better than the compiler.  For example,
  23. without typecasting, malloc() would need to have a version for char *,
  24. int *, and whatnot, and allocating memory for a user-defined structure
  25. would not be possible.  As it is, it returns a void * which is explicitly
  26. or implicitly cast to the correct type.  A more dangerous (but nonetheless
  27. oft-seen) use is to enable you to code assumptions on data.  For instance,
  28. if you have 4 chars that you know to be actually int, like so:
  29.  
  30. char really_an_int[4];
  31.  
  32. you can:
  33.  
  34. int x = *(int *)really_an_int;
  35.  
  36. Mind you, this is stinking code, but it does get used.
  37.